package net.melon.sysres.provider.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.inject.Inject;

import org.apache.commons.lang.ObjectUtils;

import net.melon.sysres.SysresUtils;
import net.melon.sysres.manager.SystemManager;
import net.melon.sysres.pojo.Attachment;
import net.melon.sysres.provider.AttachmentProvider;

public class AttachmentProviderImpl implements AttachmentProvider {
	
	private SystemManager systemManager;

	@Override
	public Attachment getAttachment(String id) {
		return systemManager.getAttachment(id);
	}

	@Override
	public Attachment saveAttachment(File templateFile, String templateFileName) throws IOException {
		return systemManager.saveAttachment(templateFile, templateFileName);
	}

	@Override
	public Attachment updateAttachment(String id, File templateFile,
			String templateFileName) throws IOException {
		return systemManager.updateAttachment(id, templateFile, templateFileName);
	}

	@Override
	public void deleteAttachment(String id) {
		systemManager.deleteAttachment(id);
	}

	@Override
	public Attachment outputAttachment(OutputStream outputStream, String id) throws IOException {
		Attachment attach = systemManager.getAttachment(id);
		File file = new File(SysresUtils.getBasicUploadPath()+attach.getUrl());
		FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);
        byte [] b=new byte[1024];//相当于我们的缓存
        long k=0;//该值用于计算当前实际下载了多少字节
        while(k<file.length()){
            int j=buff.read(b,0,1024);
            k+=j;
            //将b中的数据写到客户端的内存
            outputStream.write(b,0,j);
        }
        //将写入到客户端的内存的数据,刷新到磁盘
        outputStream.flush();
		return attach;
	}

	@Inject
	public void setSystemManager(SystemManager systemManager) {
		this.systemManager = systemManager;
	}

	@Override
	public int getOrder() {
		return 0;
	}

}
